import React, { Component } from 'react'
import { Modal, Button } from "antd";
import dayjs from 'dayjs';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { FullscreenOutlined } from "@ant-design/icons";
import { connect } from "react-redux"
import {withRouter} from "react-router-dom" //withRouter能把一个非路由组件包装成路由组件 【高阶函数】：connect调用的返回值、withRouter
import { createDeleteUserInfoAction } from "../../../redux/actions/login_action"
import {reqWeather} from "../../../api/index"
import menuArr from '../../../config/menu_config';
// import screenfull from "screenfull" (【残留问题】：screenfull库使用不了)
import "./css/header.less"
import sun from "./css/sun.jpg"

const { confirm } = Modal;

class Header extends Component {
    state = {
        date:dayjs().format('YYYY年 MM月DD日 HH:mm:ss') ,
        weatherInfo:{},
        title:''
    }

    //【勾子函数】获取天气
    getWeather = async() => {
        let result = await reqWeather()
        this.setState({weatherInfo:result})
    }

    //获取标题
    getTitle = () => {
        const pathKey = this.props.location.pathname.split('/').reverse()[0]
        let title = ''
        menuArr.forEach((item)=>{
            // 如果有孩子就遍历孩子
            if(item.children instanceof Array) {
                let tmp = item.children.find((item2)=>{
                    // 返回的是那一项
                    return item2.key === pathKey
                })
                if(tmp)  title = tmp.title
                // console.log(tmp);
            } else {
                if(item.key === pathKey) title = item.title 
            }
        })
        this.setState({title})
    }

    componentDidMount = () => {
        this.timeID = setInterval(()=>{
            this.setState({date:dayjs().format('YYYY年 MM月DD日 HH:mm:ss') })
        },1000)
        // 把获取天气的请求放在勾子函数外面，是因为不想把async添加在勾子函数上，【最好不要这样】
        this.getWeather()
        this.getTitle()   
    }
    //组件卸载时，清除循环定时器
    componentWillUnmount = () => {
        clearInterval(this.timeID)
    }

    //处理全屏
    // fullscreen = () => {
    //     screenfull.toggle();
    // }

    logout = () => {
        confirm({
            icon: <ExclamationCircleOutlined />,
            content: "你确定要退出登录吗？",
            cancelText:"取消",
            okText:"确认",
            onOk:() => {
                this.props.deleteUser()
            },
        });
    }

    
    render() {
      
        return (
            <header className="header">
                <div className="header-top">
                    <Button size="small" onClick={this.fullscreen}>
                        <FullscreenOutlined />
                    </Button>
                    <span className="username">欢迎，{this.props.userInfo.user.username}</span>
                    <Button onClick={this.logout} type="link" size="small">退出</Button>
                </div>

                <div className="header-bottom">
                    <div className="header-bottom-left">
                        {/* 页面展示名：为什么要跟随路径而不是跟随左侧导航栏名字：防止用户刷新，出现bug */}
                        
                        {this.props.titleInfo || this.state.title}
                    </div>
                    <div className="header-bottom-right">
                        {this.state.date}
                        <img alt='晴' src={sun} />
                        {this.state.weatherInfo.weather}
                        <span>温度:{this.state.weatherInfo.temperature}℃</span>
                    </div>
                </div>
            </header>
        )
    }
}

// 【常见问题】如何解决??在一般组件中使用路由组件的API(如：history(),location(),match())
//把Header包装成一个路由组件，在传给connect
let a = withRouter(Header)

export default connect(
    state => ({ userInfo: state.userInfo,titleInfo:state.titleInfo }),
    {
        deleteUser: createDeleteUserInfoAction,
    }
)(a)


